﻿using CDO;
using ADODB;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace ColorApplication
{
    public class mht : System.Web.UI.Page
    {

        public override void VerifyRenderingInServerForm(Control control)
        {
        }
        //Render webcontrol to html
        private string getHtml(Page c)
        {
            System.IO.StringWriter sw = null;
            HtmlTextWriter tw = default(HtmlTextWriter);
            try
            {
                sw = new System.IO.StringWriter();
                tw = new HtmlTextWriter(sw);
                c.RenderControl(tw);
                return sw.ToString();
            }
            finally
            {
                sw.Close();
                tw.Close();
            }
        }

        //Fix the image location so that is starts with http:// (For MS Word compatibility)
        private void fixImageLocation(ref string html, ref mhtImageCollection MHTimages)
        {
            string curContentLocation = null;
            int curIndex = 0;
            foreach (mhtImage oMhtImage in MHTimages)
            {
                curContentLocation = oMhtImage.ContentLocation;
                if (curContentLocation.IndexOf(":") == -1)
                {
                    curIndex = html.IndexOf(curContentLocation);
                    while (curIndex != -1)
                    {
                        html = html.Insert(curIndex, "http://");
                        curIndex = html.IndexOf(curContentLocation, curIndex + curContentLocation.Length);
                    }
                    oMhtImage.ContentLocation = "http://" + curContentLocation;
                }
            }
        }

        //Convert a webcontrol to a mhtml string
        public string convertWebControlToMHTString(Page control)
        {
            return convertWebControlToMHTString(control, null);
        }

        //Convert a webcontrol with its imageCollection to a mhtml string
        public string convertWebControlToMHTString(Page control, mhtImageCollection MHTimages)
        {
            //Render WebControl to html
            string html = getHtml(control);

            //If WebControl has images, make the html Word compatible
            if ((MHTimages != null))
            {
                fixImageLocation(ref html, ref MHTimages);
            }

            MessageClass msg = new MessageClass();
            ADODB.Stream stm = null;
            System.IO.MemoryStream MS = null;

            CDO.IBodyPart iBp = default(CDO.IBodyPart);

            //Make a multipart mhtml document
            CDO.IBodyPart mainBody = default(CDO.IBodyPart);
            mainBody = msg;
            mainBody.ContentMediaType = "multipart/related";

            //Make the html part of the document
            iBp = mainBody.AddBodyPart();
            iBp.ContentMediaType = "text/html";
            iBp.Charset = "UTF-8"; 
            iBp.ContentTransferEncoding = "quoted-printable";
            stm = iBp.GetDecodedContentStream();
            stm.WriteText(html);
            stm.Flush();

            //Make the image parts of the document
            if ((MHTimages != null))
            {
                foreach (mhtImage oMhtImage in MHTimages)
                {
                    iBp = mainBody.AddBodyPart();
                    var _with1 = iBp;
                    _with1.ContentMediaType = "image/" + oMhtImage.ImageFormat.ToString().ToLower();
                    _with1.ContentTransferEncoding = "base64";

                    //ContentLocation must be the same as in the html part to make them linked
                    _with1.Fields.Append("urn:schemas:mailheader:content-location", DataTypeEnum.adBSTR, 0, 0, oMhtImage.ContentLocation);
                    _with1.Fields.Update();
                    _with1.Fields.Refresh();
                    try
                    {
                        MS = new System.IO.MemoryStream();
                        oMhtImage.Image.Save(MS, oMhtImage.ImageFormat);
                        byte[] bytearray = MS.ToArray();
                        stm = iBp.GetDecodedContentStream();
                        stm.Write(bytearray);
                        stm.Flush();
                    }
                    finally
                    {
                        MS.Close();
                        stm.Close();
                    }
                }
            }

            stm = mainBody.GetStream();
            return stm.ReadText(stm.Size);
        }

        //Convert a webpage with related documents and images to a mhtml string
        public string convertWebPageToMHTString(string url)
        {
            CDO.MessageClass msg = new CDO.MessageClass();
            ADODB.Stream stm = null;

            try
            {
                msg.MimeFormatted = true;
                msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
                stm = msg.GetStream();
                return stm.ReadText(stm.Size);
            }
            finally
            {
                stm.Close();
            }
        }

        //Send a mhtml string as a mhtml Word document to the client
        public void sendMHTFile(string MHTString, string fileName)
        {
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/mht";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.Write(MHTString);
            Response.Flush();
            Response.Close();
        }
    }
}